package com.cucn.ingmall.ware.listener;

import com.cucn.common.constant.ware.WareConstant;
import com.cucn.common.to.mq.OrderTO;
import com.cucn.common.to.mq.StockLockedTO;
import com.cucn.ingmall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author KouChaoJie
 * @since: 2022/1/26 14:59
 */
@Service
@Slf4j
@RabbitListener(queues = WareConstant.STOCK_RELEASE_STOCK_QUEUE)
public class StockReleaseListener {

    @Resource
    private WareSkuService wareSkuService;

    /**
     * 处理mq消息方法
     * 库存自动解锁
     * 下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚。
     * 之前锁定的库存就要自动解锁。
     * <p>
     * 如果锁库存失败,库存会整体回滚,所以工作单有可能会没有数据
     * <p>
     * 只要解锁库存的消息失败,一定要告诉服务器此次解锁失败,重新解锁
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTO stockLockedTO, Message message, Channel channel) throws IOException {
        log.info("收到解锁库存的消息");
        try {
            wareSkuService.unLockStock(stockLockedTO);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据库存过期消息解锁库存失败,重试....{}", e.getMessage());
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    /**
     * 处理订单关单后的消息,进行库存解锁
     */
    @RabbitHandler
    public void handleOrderCloseRelease(OrderTO orderTO, Message message, Channel channel) throws IOException {
        log.info("收到订单关单的消息,准备解锁库存");
        try {
            wareSkuService.unLockStock(orderTO);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据订单关单消息解锁库存失败,重试....{}", e.getMessage());
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
